from flask import render_template,redirect,Response,session
import dbtools  # 自己写的py，里面写了一些下面需要调用的函数
import json
import flask
from datetime import datetime,timedelta
server = flask.Flask(__name__)
server.config['SECRET_KEY'] = '123456'
server.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=10)
# 新建一个服务，把当前这个python文件当做一个服务
@server.route('/')
def index():
    return render_template('login.html')


@server.route('/lguot')
def lguot():
    session['sessionid'] = ''
    return render_template('login.html')

# 开发一个登录接口
@server.route('/login/', methods=['post'])
def login():
    uname = flask.request.form.get('username')
    pd = flask.request.form.get('passwd')
    sql = 'select * from user where name="%s"' % uname
    res = dbtools.my_db(sql)  # tools里的函数：连接数据库，执行sql并返回结果
    if res:
        if pd == res.get('pass'):  # tools里的函数，加密密码
            # res = {"code": 0, "msg": "登录成功！"}
            session['sessionid'] = 'uname'
            return redirect('/list')
        else:
            res = {"code": 1, "msg": "密码错误！"}
            return render_template('login.html')
    else:
        res = {'code': 2, "msg": "用户不存在"}
        return render_template('login.html')

 # http://192.168.31.158:8998/query?id=2
@server.route('/query', methods=['get'])
def queryone():
    id = flask.request.values.get('id')
    sql = 'select * from user where id="%s"' % id
    res = dbtools.my_db(sql)  # tools里的函数：连接数据库，执行sql并返回结果
    return json.dumps(res, ensure_ascii=False, indent=4)  # 输出json格式

# http://192.168.31.158:8998/list
@server.route('/list', methods=['get'])
def queryall():
    if(session.get('sessionid') ==''):
        return render_template('login.html')
    sql = 'select * from user '
    res = dbtools.my_dball(sql)  # tools里的函数：连接数据库，执行sql并返回结果
    print(res)

    return render_template('list.html', userlist = res)

@server.route('/add/')
def add():
    if (session.get('sessionid') ==''):
        return render_template('login.html')
    return render_template('add.html')
@server.route('/addaction/', methods = ['POST'])
def addaction():
    if (session.get('sessionid') =='' ):
        return render_template('login.html')
    username = "'"+flask.request.form.get('username')+"'"
    password = "'"+flask.request.form.get('password')+"'"
    age = "'"+flask.request.form.get('age')+"'"

    sql = 'INSERT INTO user(name,age,pass) VALUES (%s, %s, %s)'%(username,age,password)
    print(sql)
    dbtools.my_dbinsert(sql)
    return redirect('/list')


 # http://192.168.31.158:8998/delete?id=3
@server.route('/delete/', methods=['get'])
def delete():
    if (session.get('sessionid') =='' ):
        return render_template('login.html')
    id = flask.request.values.get('id')
    sql = "delete from user where id='"+id+"'"
    res = dbtools.my_dbdelete(sql)  # tools里的函数：连接数据库，执行sql并返回结果
    return  redirect('/list')

@server.route('/update/')
def update():
    if (session.get('sessionid') =='' ):
        return render_template('login.html')
    id = flask.request.values.get('id')
    sql = 'select * from user where id="%s"' % id
    res = dbtools.my_db(sql)
    user = [id,res['name'], res['age'],res['pass']]
    print(user)
    return render_template('update.html', user = user)


# http://192.168.31.158:8998/update?id=2&name=llk
@server.route('/updateaction/', methods=['post'])
def updateaction():
    if (session.get('sessionid') =='' ):
        return render_template('login.html')
    id = flask.request.form.get('id')
    name = flask.request.form.get('username')
    age = flask.request.form.get('age')
    password = flask.request.form.get('password')
    print(name)
    print(age)
    print(password)
    ss=''
    if(name!=""):
     ss='name="'+name+'"'
    if (age != ""):
        ss=ss+",age="+age
    if (password != ""):
        ss=ss+",pass="+password
    sql = 'update user set '+ss+' where id='+ id
    print(sql)
    res = dbtools.my_dbupdate(sql)  # tools里的函数：连接数据库，执行sql并返回结果
    return redirect('/list')

server.run(host='0.0.0.0', port=8998, debug=True)  # 若别人访问这个接口，则host需要输入自己的ip地址，而不是127.0.0.1

# 以上接口访问地址即：http://127.0.0.1:8998/login?username=hello&passwd=123
